package com.kaifamiao.preventrefresh;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public RedisService(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, String value) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(key, value, 1, TimeUnit.MINUTES); // 设置值时设置过期时间为1分钟
    }

    public void set(String key, String value,int N) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(key, value, N, TimeUnit.MINUTES); // 设置值时设置过期时间为N分钟
    }

    public String get(String key) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        return operations.get(key);
    }

    public Long incr(String key, long delta) {
        return performIncrement(key, delta);
    }

    public Long incr(String key) {
        return performIncrement(key, 1); // 使用默认增量 1
    }

    private Long performIncrement(String key, long delta) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        // 检查键是否存在，如果不存在，则设置初始值为 0 并设置过期时间
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(key))) {
            operations.set(key, "0", 1, TimeUnit.MINUTES); // 设置过期时间为 1 分钟
        }

        return operations.increment(key, delta);
    }
}
